package com.yonyou.brigade.third_parties.zteitc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.props.PropUtil;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.zteitc.dao.ZteUserMapper;
import com.yonyou.brigade.third_parties.zteitc.model.ZteUser;
import com.yonyou.brigade.third_parties.zteitc.service.IZteUserService;
import com.yonyou.brigade.third_parties.zteitc.service.IZteitcPublicService;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.util.operateutil.CompareUtils;
import com.yonyou.ybzboot.starter.facade.result.FacadeResult;
import com.yonyou.ybzboot.uc.client.UcTenantServiceClient;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import com.yonyou.ybzboot.uc.model.UcTenantService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author houyb@yonyou.com
 * @since 2018-12-24
 */
@Service
public class ZteUserServiceImpl extends ServiceImpl<ZteUserMapper, ZteUser> implements IZteUserService {

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService briChannelService;

    @Autowired
    private PropUtil propUtil;

    @Autowired
    private UcTenantServiceClient ucTenantServiceClient;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService iUserCenterService;

    @Autowired
    @Qualifier("zteitcPublicServiceImpl")
    private IZteitcPublicService zteitcPublicService;

    @Value("${zteitc.getAccountingDepartmentUrl}")
    String getAccountingDepartmentUrl;

    @Value("${ybz.baseUrl}")
    private String ybzBaseUrl;

    private String CompareProperties = "employeeNumber,employeeName,mobilePhone,email,enabledFlag,ownerName,deptCode,userProperty1";

    private static final Logger logger = LoggerFactory.getLogger(IZteitcPublicService.class);


    @Override
    public String loginUrl(String tenant, String org, String phone, String pageType, String pcOrH5, String jsonExt) {
        String resultUrl = "";
        BriChannel briChannel = briChannelService.getEnableInfoByTenantOrg(tenant, org, "zteitc");
        if (briChannel == null) {
            // 调用公共服务，查询是否正在开通中
            FacadeResult<List<UcTenantService>> result = ucTenantServiceClient.queryOpenService(tenant, "brigade");
            if (!CollectionUtils.isEmpty(result.getData())) {
                resultUrl = propUtil.getON_OPEN_URL();
                return resultUrl;
            }
            resultUrl = propUtil.getNO_ACCESS_URL();
            return resultUrl;
        } else {
            Wrapper<ZteUser> zteUserWrapper = new EntityWrapper<>();
            zteUserWrapper.eq("mobile_phone", phone);
            zteUserWrapper.eq("tenant", tenant);
            List<ZteUser> zteUsers = this.baseMapper.selectList(zteUserWrapper);
            UcUserDto ucUserDtoByPhone = iUserCenterService.listCompleteUcUserByUserMobiles4admin(phone, tenant);
            ZteUser zteUser = getZteUser(new ZteUser() , ucUserDtoByPhone ,tenant);
            if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
                //酷开网络，定制化需求：同步人员的同时同步一级部门信息
                {
                    if ("gztx1qwa".equals(tenant)) {
                        //调用友报账接口查询该人的一级部门
                        JSONObject queryData = new JSONObject();
                        queryData.put("tenant", tenant);
                        queryData.put("userCode", ucUserDtoByPhone.getPersonCode());
                        queryData.put("pkDept", ucUserDtoByPhone.getDeptPk());
                        queryData.put("pkOrg", org);
                        String result = HttpClientUtil.doPostJson(ybzBaseUrl + getAccountingDepartmentUrl, queryData.toJSONString());
                        String accountingDepartmentPk = "";
                        String accountingDepartmentName = "";
                        try {
                            JSONArray depatementArr = JSONArray.parseArray(result);
                            if (depatementArr != null) {
                                accountingDepartmentPk = depatementArr.getJSONObject(0).getString("PK_DEPT");
                                accountingDepartmentName = depatementArr.getJSONObject(0).getString("NAME");
                            }
                        } catch (Exception e) {
                            logger.info("调用友报账接口查询该人的一级部门失败：[" + queryData.toJSONString() + "] " + result);
                        }
                        zteUser = getZteUser(new ZteUser(), ucUserDtoByPhone, tenant, accountingDepartmentPk,accountingDepartmentName);
                    }
                }
                //如果没查到进行人员同步
                if (zteUsers == null || zteUsers.size() == 0) {
                    List<ZteUser> list = new ArrayList<ZteUser>();
                    list.add(zteUser);
                    zteitcPublicService.syncZteitcSingleUserByPhone(list, briChannel);
                    this.baseMapper.insert(zteUser);
                    zteUsers = this.baseMapper.selectList(zteUserWrapper);
                    if (zteUsers == null || zteUsers.size() == 0) {
                        resultUrl = propUtil.getNO_ACCESS_URL();
                        return resultUrl;
                    }
                } else {
                    //如果已经同步过，检查信息是否有变化，如果有变化则更新
                    Map<String, String> compareMap = new HashMap<>();

                    String[] compareFields = CompareProperties.split(",");
                    if (compareFields != null && compareFields.length > 0) {
                        for (int i = 0; i < compareFields.length; i++) {
                            //此处只需要key值
                            compareMap.put(compareFields[i], "");
                        }
                    }
                    Map<String, Object> compareResult = CompareUtils.getModifyContent(zteUsers.get(0), zteUser, compareMap);
                    if (compareResult != null && compareResult.size() > 0) {
                        //更新已经同步过的用户信息
                        List<ZteUser> list = new ArrayList<ZteUser>();
                        list.add(zteUser);
                        zteitcPublicService.syncZteitcSingleUserByPhone(list, briChannel);
                        zteUser.setId(zteUsers.get(0).getId());
                        this.baseMapper.updateById(zteUser);
                    }
                }
            }
            JSONObject configJSON = JSONObject.parseObject(briChannel.getConfig());
            resultUrl = zteitcPublicService.ssoLogin(zteUser, pageType, configJSON);
            if (resultUrl == null || "".equals(resultUrl)) {
                resultUrl = propUtil.getNO_ACCESS_URL();
                return resultUrl;
            }

        }
        return resultUrl;
    }


    public ZteUser getZteUser(ZteUser zteUser , UcUserDto ucUserDtoByPhone, String tenant){
        zteUser.setEmployeeNumber(ucUserDtoByPhone.getPersonCode());
        zteUser.setEmployeeName(ucUserDtoByPhone.getUserName());
        zteUser.setMobilePhone(ucUserDtoByPhone.getPhone());
        zteUser.setEmail(ucUserDtoByPhone.getEmail());
        zteUser.setEnabledFlag(ucUserDtoByPhone.getValid().intValue()==1?"Y":"N");
        zteUser.setCardType("0");
        zteUser.setOwnerName(ucUserDtoByPhone.getUserName());
        zteUser.setCardNum(ucUserDtoByPhone.getPassengerId());
        zteUser.setDeptCode(ucUserDtoByPhone.getDeptCode());
        zteUser.setUserProperty1(ucUserDtoByPhone.getPostName());
        zteUser.setTenant(tenant);
        return  zteUser;
    }
    //重载，酷开网络的zteuser变量的deptcode用的是一级部门，其他租户用的用户中心的部门
    public ZteUser getZteUser( ZteUser zteUser , UcUserDto ucUserDtoByPhone, String tenant, String accountingDepartmentPk , String accountingDepartmentName) {
        getZteUser(zteUser,ucUserDtoByPhone,tenant);
        zteUser.setDeptCode(accountingDepartmentPk);
        zteUser.setDeptName(accountingDepartmentName);
        return zteUser;
    }

}
